<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>

        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import?type=user')">excel导入</el-button>
          <el-button type="danger" size="small" @click="clickExport">excel导出</el-button>
          <el-button type="primary" size="small" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>
      <add-emp :show-dialog.sync="showDialog" />

      <el-card style="margin-top: 10px;">
        <el-table v-loading="loading" border :data="list">
          <el-table-column label="序号" type="index" sortable="" />
          <el-table-column label="姓名" prop="username" sortable="" />
          <el-table-column>
            <template #default="{ row }">
              <img v-imgerror="defaultImage" class="staff" :src="row.staffPhoto || defaultImage" alt="" @click="clickShowCodeDialog(row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column label="手机号" prop="mobile" sortable="" />
          <el-table-column label="工号" prop="workNumber" sortable="" />
          <el-table-column label="聘用形式" prop="formOfEmployment" :formatter="formatEmployment" sortable="" />
          <el-table-column label="部门" prop="departmentName" sortable="" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable="">
            <template v-slot="{row}">
              {{ row.timeOfEntry | formatDay }}
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template v-slot="{row}">
              <el-button
                type="text"
                size="small"
                :disabled="!checkPermission('POINT-USER-UPDATE')"
                @click="$router.push(`/employees/detail/${row.id}`)"
              >查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
              <el-button type="text" size="small" :disabled="!checkPermission('POINT-USER-UPDATE')" @click="delEmp(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-dialog width="300px" title="二维码" :visible="showCodeDialog" @close="showCodeDialog=false">
          <el-row type="flex" justify="center">
            <canvas ref="myCanvas" />
          </el-row>
        </el-dialog>

        <assign-role :show-role-dialog.sync="showRoleDialog" :user-id="userId" />

        <!-- 分页组件 -->
        <div style="height: 60px; margin-top: 10px">
          <el-pagination
            :total="total"
            :current-page="page"
            :page-size="pagesize"
            layout="prev, pager, next"
            @current-change="handleCurrentChange"
          />
        </div>

      </el-card>
    </div>
  </div>
</template>

<script>
import defaultImage from '@/assets/common/2.webp'
import { reqGetEmpList, reqDelEmp } from '@/api/employees'
// 枚举类
import EmployeeEnum from '@/api/constant/employees'
import AddEmp from './components/AddEmp.vue'
import { formatDate } from '@/filters'
import QrCode from 'qrcode'
import AssignRole from './components/assign-role.vue'

export default {
  name: 'Employees',
  components: { AddEmp, AssignRole },
  data() {
    return {
      list: [],
      page: 1,
      pagesize: 10,
      total: 0,
      loading: false,
      showDialog: false,
      defaultImage,
      showCodeDialog: false,
      showRoleDialog: false,
      userId: ''
    }
  },
  computed: {
    type() {
      return this.$route.query.type
    }
  },
  created() {
    this.getEmpList()
  },
  methods: {
    async getEmpList() {
      this.loading = true
      const { data: res } = await reqGetEmpList(this.page, this.pagesize)
      // console.log(res)
      const { total, rows } = res
      this.total = total
      this.list = rows
      this.loading = false
    },
    handleCurrentChange(newPage) {
      this.page = newPage
      this.getEmpList()
    },
    // 格式化聘用形式
    formatEmployment(row, column, cellValue, index) {
      const obj = EmployeeEnum.hireType.find(item => item.id === cellValue)
      return obj ? obj.value : '未知'
    },
    async delEmp(id) {
      const res = await this.$confirm('确定要删除该员工吗？', '温馨提示').catch(error => error)
      if (res !== 'confirm') return
      await reqDelEmp(id)
      if (this.list.length === 1 && this.page > 1) this.page--
      this.$message.success('删除成功')
      this.getEmpList()
    },
    async clickExport() {
      // 请注意: 如果导出的是当前页, 那么数据, this.list 即可,
      // 但是我们一般导出的是全部的数据, 需要请求到所有的数据
      const { data: { rows }} = await reqGetEmpList(1, this.total)
      const headersArr = ['姓名', '手机号', '入职日期', '聘用形式', '转正日期', '工号', '部门']
      const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
      const headersRelations = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const dataArr = this.formatJson(rows, headersArr, headersRelations)
      const merges = ['A1:A2', 'B1:F1', 'G1:G2']

      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: headersArr, // 表格的头部
          // 二维数组 [ [], [], [] ]
          data: dataArr,
          filename: '学生信息表', // 导出的excel文件名
          autoWidth: true, // 是否开启单元格宽度自适应
          bookType: 'xlsx', // 类型
          multiHeader,
          merges
        })
      })
    },

    // 将表头数据和数据进行对应
    formatJson(rows, headersArr, headersRelations) {
      // [
      //   [ 值1, 值2, 值3, ... ]
      // ]
      const resultsArr = rows.map((item) => {
        const arr = []
        headersArr.forEach(key => {
          const englishKey = headersRelations[key]
          let value = item[englishKey]
          if (['timeOfEntry', 'correctionTime'].includes(englishKey)) {
            value = formatDate(value)
          }
          if (englishKey === 'formOfEmployment') {
            const obj = EmployeeEnum.hireType.find(obj => obj.id === +value)
            value = obj ? obj.value : '未知'
          }
          arr.push(value)
        })
        return arr
      })
      return resultsArr
    },
    clickShowCodeDialog(url) {
      if (!url) return // 有图片才显示弹层
      this.showCodeDialog = true
      this.$nextTick(() => {
        // 如果这里 url 写的是网址, 就会跳转到对应网址 (二维码分享效果)
        QrCode.toCanvas(this.$refs.myCanvas, 'https://gitee.com/tingzhi2001/vue_hr')
      })
    },
    editRole(id) {
      this.userId = id
      this.showRoleDialog = true
    },
    // 控制是否有权限
    checkPermission(key) {
      console.log(this.$store.getters.roles)
      if (this.$store.getters.roles) {
        return this.$store.getters.roles.points.includes(key)
      } else {
        return false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.employees-container {
  .staff {
    width: 70px;
    height: 70px;
    border-radius: 50%;
  }
}
</style>
